import { defineStore } from 'pinia'
import { useStore2 } from './store2'

// 使用options API模式定义
export const useCounterStore = defineStore('counter', {
  state: () => ({ 
    count: 0,
    name:'rouzi',
    user:[
      {
        name:'aa',
        id:1,
      },{
        name:'bb',
        id:2,
      }
    ]
  }),
  getters: {
    // 使用箭头函数，第一个参数为state
    double: state => state.count * 2,
    // 访问其他getter，使用this访问其他getter
    getOtherGetter(){ return this.double },
    // 带参数getters， 返回一个函数
    getUserById:state =>{
      return (id) =>state.user.find(user=>user.id==id)
    },
    // 访问其他 Store 的getter
    getOtherStoreGetter(state){
      const otherStore = useStore2()
      return state.name +','+ otherStore.getData
    }
  },
  actions: {
    // 普通action
    increment() {
      this.count++
    },
    // 异步action
    async getUserInfo(name){
      try {
        const user = await asyncFunction(name)
        console.log("11111")
        this.name = user.name
      } catch (error) {      
        console.log(error)        
      }
    }
  },
  // 持久化存储
  persist: {
    enabled: true, // 开启
    strategies: [
      {
        key: 'mykey',  // 设置key
        storage: localStorage, // 设置存储方式 sessionStorage、localStorage，默认sessionStorage
        paths:['count'] // 设置需要存储的state，默认全部
      },
      // 可设置多个
      {
        key: 'mykey2',  
        storage: localStorage, 
        paths:['user'] 
      },
    ],
  }
})

function asyncFunction(name){
  return new Promise((resolve,reject)=>{
    setTimeout(() => {
      console.log("2秒后")
      if(name!='rzz'){
        reject('错了错')
      }else{
        resolve({name:name}) 
      }
    }, 2000);
  })
  
}
